package com.ytktt.study.week3.task346.gateway.filter;

import com.ytktt.study.week3.task346.gateway.properties.ApplicationProperties;
import com.ytktt.study.week3.task346.gateway.util.RequestUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Order(1)
public class BlacklistHttpRequestFilter implements HttpRequestFilter {

    private final List<String> blacklist;

    public BlacklistHttpRequestFilter(ApplicationProperties applicationProperties) {
        ApplicationProperties.RequestProperties requestProperties = applicationProperties.getRequest();
        this.blacklist = requestProperties.getBlackUrls();
    }

    @Override
    public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
        String ipAddress = RequestUtil.getIpAddress(fullRequest, ctx);
        if (this.blacklist.contains(ipAddress)) {
            // 拒绝处理
            ctx.close();
            return;
        }
        fullRequest.headers().set("X-REAL-IP", ipAddress);
    }
}
